﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using Db8.Data;
using Db8.DataAccess;
using Db8.ViewModels;
using System.Web.Helpers;

namespace Db8.Controllers
{
    public class HomeController : ControllerBase
    {
        private Db8Context db = new Db8Context();

        public ActionResult Index()
        {
            if (Request.IsSupportedMobileDevice())
                return RedirectToAction("Index", "Mobile");
            return View();
        }

        public ActionResult ViewMode(string mode)
        {
            if (mode == "full" || mode == "mobile")
            {
                ClientSettings.ViewMode = mode;
            }
            else
            {
                ClientSettings.ViewMode = "";
            }
            return RedirectToAction("Index");
        }

        public ActionResult Browse()
        {
            int count = 10;
            var model = new BrowseViewModel()
            {
                Popular = db.GetPopularKeywords(count),
                Recent = db.GetRecentKeywords(count)
            };
            return View(model);
        }


        public ViewResult Search(string search)
        {
            try
            {
                // only show results with counters
                if (!string.IsNullOrEmpty(search))
                {
                    List<Claim> results = db.SearchClaims(search, 20, true, false);
                    return View("Search", results);
                }

                return View("Search", new List<Claim>());
            }
            catch (Exception ex)
            {
                Logger.LogException(null, ex);
                //ViewBag.ErrorDetails = ex.Message + ex.StackTrace;
                return View("Error");
            }
        }

        string cookieName = "rsp";

        public ActionResult Summary()
        {
            string rsp = Request.Cookies.AllKeys.Contains(cookieName)
                ? Request.Cookies[cookieName].Value
                : "";
            rsp = HttpUtility.UrlDecode(rsp);
            if (string.IsNullOrEmpty(rsp))
                return View(new List<ClaimViewModel>());

            var counters = rsp
                .Split('|')
                .Select(s => 
                new {
                    ClaimId = int.Parse(s.Split('/')[0]),
                    CounterClaimId = int.Parse(s.Split('/')[1])
                }).ToList();



            List<int> ids = counters.Select(c => c.ClaimId)
                .Union(counters.Select(c => c.CounterClaimId))
                .ToList();

            var claims = db.Claims
                //.Include("CounteredClaims")
                //.Include("CounteredClaims.Claim")
                .WhereIn(c => c.ClaimId, ids)
                .ToList()
                .OrderBy(c => ids.IndexOf(c.ClaimId))
                .ToList();

            List<ClaimViewModel> countered = new List<ClaimViewModel>();
            foreach (var c in counters)
            {
                var alreadyCountered = countered.Where(claim => claim.Claim.ClaimId == c.ClaimId).FirstOrDefault();
                if (alreadyCountered == null)
                {
                    alreadyCountered = ClaimViewModel.FromClaim(claims.Where(claim => claim.ClaimId == c.ClaimId).FirstOrDefault());
                    if (alreadyCountered != null)
                    {
                        alreadyCountered.CounterClaims = new List<ClaimViewModel>();
                        countered.Add(alreadyCountered);
                    }
                }

                if (alreadyCountered != null)
                {
                    if (!alreadyCountered.CounterClaims.Any(cc => cc.Claim.ClaimId == c.CounterClaimId))
                    {
                        var cc = claims.Where(claim => claim.ClaimId == c.CounterClaimId).FirstOrDefault();
                        if (cc != null)
                        {
                            alreadyCountered.CounterClaims.Add(ClaimViewModel.FromClaim(cc));
                        }
                    }
                }
                
            }

            return View(countered);
        }

        public ActionResult Reset()
        {
            var cookie = new HttpCookie(cookieName);
            cookie.Expires = DateTime.Now.AddDays(-1);
            Response.Cookies.Add(cookie);
            return RedirectToAction("Index");
        }


        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }

    }
}
